/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.figures;


import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.gef.requests.CreateConnectionRequest;
import org.eclipse.gef.requests.ReconnectRequest;
import org.eclipse.uml2.uml.Message;
import org.eclipse.uml2.uml.NamedElement;

import com.cea.papyrus.diagram.sequence.sedi.editor.MessageSpecification;
import com.cea.papyrus.diagram.sequence.sedi.model.util.ModelUtil;
import com.cea.papyrus.diagraminterchange2.di2.GraphEdge;

/**
 * TODO Document TODO Share code with other anchor policies.
 * 
 * @author frankd@ifi.uio.no
 */
public class InteractionAnchorPolicy implements AnchorPolicy {
    public boolean acceptConnectionCreate(ConnectionAnchor anchor, CreateConnectionRequest request) {
        return request.getNewObject() instanceof MessageSpecification;
    }

    public boolean acceptConnectionComplete(ConnectionAnchor anchor, CreateConnectionRequest request) {
        return check(request.getNewObject(), request.getSourceEditPart(), request
                .getTargetEditPart());
    }

    @SuppressWarnings("unchecked")
    public boolean acceptReconnectSource(ConnectionAnchor anchor, ReconnectRequest request) {
        return check(ModelUtil.<NamedElement> getSemantic((GraphEdge) request
                .getConnectionEditPart().getModel()), request.getTarget(), // actually
                // gives the
                // new source
                request.getConnectionEditPart().getTarget());
    }

    @SuppressWarnings("unchecked")
    public boolean acceptReconnectTarget(ConnectionAnchor anchor, ReconnectRequest request) {
        return check(ModelUtil.<NamedElement> getSemantic((GraphEdge) request
                .getConnectionEditPart().getModel()), request.getConnectionEditPart().getSource(),
                request.getTarget());
    }

    private boolean check(Object connection, Object source, Object target) {
        // Don't allow messages to self
        // Also only allow real messages
        return (source != target && (connection instanceof Message || connection instanceof MessageSpecification));
        // || connection == UMLFactory.eINSTANCE.getMessage()));
    }
}
